package DoublyLinkedListSentinel2;


import java.util.Iterator;

public class DoublyLinkedListSentinel2 implements Iterable<Integer> {
    public DoublyLinkedListSentinel2() {
        sentinel.prev = sentinel;
        sentinel.next = sentinel;
    }

    @Override
    public Iterator<Integer> iterator() {
        return new Iterator<Integer>() {
            Node p = sentinel.next;
            @Override
            public boolean hasNext() {
                return p != sentinel;
            }

            @Override
            public Integer next() {
                int value = p.value;
                p = p.next;
                return value;
            }
        };
    }


    private static class Node {
        Node prev;
        int value;
        Node next;

        public Node(Node prev, int value, Node next) {
            this.prev = prev;
            this.value = value;
            this.next = next;
        }
    }
    private Node sentinel = new Node(null, -1, null);


    public void addFirst(int value) {
        Node a = sentinel;
        Node b = sentinel.next;
        Node add = new Node(a, value, b);
        a.next = add;
        b.prev = add;
    }

    public void addLast(int value) {
        Node a = sentinel.prev;
        Node b = sentinel;
        Node add = new Node(a, value, b);
        a.next = add;
        b.prev = add;
    }
   public void removeFirst(){
        Node remove = sentinel.next;
        if(remove == sentinel){
            throw new IllegalArgumentException("非法");
        }
        Node p = remove.next;
        sentinel.next = p;
        p.prev = sentinel;
   }
   public void removeLast(){
        Node remove = sentinel.prev;
       if(remove == sentinel){
           throw new IllegalArgumentException("非法");
       }
        Node p = remove.prev;
        sentinel.prev = p;
        p.next = sentinel;
   }
   public void removeByValue(int value){
       Node remove = findByValue(value);
       if(remove == null){
           return;
       }
       Node a = remove.prev;
       Node b = remove.next;
       a.next = b;
       b.prev = a;
   }
   public Node findByValue(int value){
        Node p = sentinel.next;
        while(p != sentinel){
            if(p.value == value){
                return p;
            }
            p = p.next;
        }
        return null;
   }
}